<?php

namespace Biz\service\BrandRights;

use Biz\model\brand\Brand;
use Biz\model\brand\Content as mBrandContent;
use Biz\model\brandAccount\BrandAccountInfo;
use Biz\model\brandRights\BrandLevelRights;
use Biz\model\brandRights\BrandLevelRights as mBrandLevelRights;
use Biz\model\brandRights\BrandPackageRights;
use Biz\model\brandRights\BrandPackageRightsConfig;
use Biz\model\brandRights\BrandRightsAll;
use Biz\model\brandRights\BrandRightsRecored;
use Biz\model\brandRights\BrandRightsSource;
use Biz\pockets\constInterface\BrandLevel;
use Biz\pockets\constInterface\SourceRightsInterface;
use Biz\pockets\serviceTrait\_Async;
use Biz\tools\helper\Common;
use Doraemon\cache\EsUpdateCollector;
use Doraemon\pockets\datebase\BaseDbModel;
use Doraemon\tools\Log;

class BrandRightsAllService
{
    use _Async;

    /**
     * 获取品牌(有效)权益
     * @param int $brandId
     * @param  $field
     * @return array
     */
    public static function getBrandSourceInfos($brandId, $field = "*"): array
    {
        $where['rights_status'] = BaseDbModel::STATUS_NORMAL;
        $where['brand_id'] = $brandId;
        $where['end_time[>=]'] = time();
        return BrandRightsAll::selectList($where, $field);
    }

    /**
     * 获取品牌权益状态列表
     * @param $brandId
     * @return array
     */
    public static function getBrandSourceList($brandId): array
    {
        $field = ['rights_num', 'rights_source_id'];

        $ownSourceList = self::getBrandSourceInfos($brandId, $field);
        if ($ownSourceList) {
            $ownSourceList = array_column($ownSourceList, null, 'rights_source_id');
        }

        $allSourceList = BrandRightsSourceService::getAllSourceList([
            'rights_name',
            'rights_title',
            'rights_type',
            'id'
        ]);

        foreach ($allSourceList as $item) {
            $status = "on";
            if (!isset($ownSourceList[$item['id']])) {
                $status = "off";
                $ownSourceList[$item['id']]['rights_num'] = 0;
            }
            $ownSourceList[$item['id']]['rights_name'] = $item['rights_name'];
            $ownSourceList[$item['id']]['rights_type'] = $item['rights_type'];
            $ownSourceList[$item['id']]['rights_title'] = $item['rights_title'];
            $ownSourceList[$item['id']]['status'] = $status;
        }
        return array_column($ownSourceList, null, 'rights_name');
    }

    /**
     * 获取品牌(有效)指定权益可使用数量
     * @param int $brandId
     * @param $rightsName //权益名称
     * @return int 无权益返回0
     */
    public static function getBrandSourceNum(int $brandId, $rightsName): int
    {
        $rid = BrandRightsSourceService::getIdByRightsName($rightsName);
        if (!$rid) {
            return 0;
        }
        $where['brand_id'] = $brandId;
        $where['rights_status'] = BaseDbModel::STATUS_NORMAL;
        $where['rights_source_id'] = $rid;
        $rights_num = BrandRightsAll::get('rights_num', $where);
        if (!$rights_num) {
            return 0;
        }
        return $rights_num;
    }

    /**
     * @param $rightsNum
     * @param $totalNum
     * @param $brandId
     * @param $rightsId
     * @param array $dataExt
     * @return bool
     */
    public static function updateRightsAll($rightsNum, $totalNum, $brandId, $rightsId, array $dataExt = []): bool
    {
        $data['rights_num'] = $rightsNum ?? 0;
        $data['total_num'] = $totalNum;
        $data = array_merge($data, $dataExt);
        $where['brand_id'] = $brandId;
        $where['rights_source_id'] = $rightsId;
        $res = BrandRightsAll::updateData($data, $where);
        if (!$res) {
            return false;
        }
        return true;
    }

    /**
     * 获取 好物轻测活动可用数量（包括混合套餐数量）
     * @param $brandId
     * @return array
     */
    public static function getGoodTestPackNum($brandId): array
    {
        //混合套餐数量
        $mixNum = self::getMixPackNum($brandId);
        //好物轻测套餐
        $actPack = SourceRightsInterface::GOODS_TEST;

        $where['rights_status'] = BaseDbModel::STATUS_NORMAL;
        $where['brand_id'] = $brandId;
        $where['end_time[>=]'] = time();
        $where['rights_name'] = $actPack;
        //todo查询修改
        $sourceList = BrandRightsAll::selectList($where, ['rights_name', 'rights_num']);
        $sourceList = array_column($sourceList, 'rights_num', 'rights_name');
        $packageArr = [];
        foreach ($actPack as $package => $item) {
            if (isset($sourceList[$item]) && $sourceList[$item]) {
                $packageArr[$package] = $sourceList[$item];
            } else {
                $packageArr[$package] = 0;
            }
        }

        $goodsTestAKey = array_search(SourceRightsInterface::GOODS_TEST_A, $actPack);
        $packageArr[$goodsTestAKey] += $mixNum;
        return $packageArr;

    }

    /**
     * 获取混合套餐数量
     * @param $brandId
     * @return int
     */
    public static function getMixPackNum($brandId): int
    {
        return self::getBrandSourceNum($brandId, SourceRightsInterface::NEW_PRODUCT_GOODS_TEST_A);
    }

    /**
     * 异步处理成功创建支付品牌套餐之后处理品牌权益
     */
    public static function afterBrandOrder($orderInfo)
    {
        Log::info('after order', $orderInfo);
        self::_async($orderInfo);
    }

    /**
     * 成功创建支付品牌套餐之后处理品牌权益
     * @param $orderInfo
     * @return bool|mixed
     */
    public static function _async_afterBrandOrder($orderInfo)
    {
        Log::info('after order async', $orderInfo);
        $brandId = $orderInfo['brand_id'];
        $uid = $orderInfo['uid'];
        $packId = $orderInfo['package_id'];
        $dsn = $orderInfo['dsn'];
        $adminId = $orderInfo['admin_id'];
        //查询Record订单是否存在，存在则直接返回true;
        $record = BrandRightsRecoredService::getRecordByDsn($brandId, $dsn);
        if (!empty($record)) {
            return true;
        }

        $packageRights = self::getPackageRights($packId);
        $packageRightsSourceIds = array_values(array_column($packageRights, 'rights_source_id'));
        $rightsSourceMap = self::getPackageRightsSourceMap($packageRightsSourceIds);
        $orderInfoParams = [
            'dsn' => $dsn,
            'in_start_time' => $orderInfo['in_start_time'],
            'in_end_time' => $orderInfo['in_end_time']
        ];
        $transData = self::createTransactionData($brandId, $orderInfoParams, $packageRights, $rightsSourceMap,
            $adminId);
        if (empty($transData)) {
            return false;
        }
        $tResult = BrandRightsAll::action(function () use ($transData) {
            foreach ($transData as $rightsSourceId => $transAction) {
                foreach ($transAction as $className => $actionData) {
                    foreach ($actionData as $action => $data) {
                        $result = call_user_func_array([$className, $action], $data);
                        if (!$result) {
                            Log::debug('after order,modify rights fail', [
                                'action' => "{$className}::{$action}",
                                'params' => $data
                            ]);
                            return false;
                        }
                    }
                }

            }
            return true;
        });

        //恢复品牌等级保留权益
        $startTime = strtotime($orderInfo['in_start_time']);
        $endTime = strtotime($orderInfo['in_end_time']);
        $endTime = strtotime(date('Y-m-d 23:59:59', $endTime));
        BrandLevelRightsService::levelRightsRecovery($brandId, $startTime, $endTime);

        self::esCacheUpdate([$uid], [$brandId]);

        return $tResult;
    }

    /**
     * 构造事务数据
     * @param $brandId
     * @param $orderInfo
     * @param $packageRights
     * @param $rightsSourceMap
     * @return array
     */
    public static function createTransactionData($brandId, $orderInfo, $packageRights, $rightsSourceMap, $adminId = 0)
    {
        $transData = [];
        $curTime = time();
        $startTime = isset($orderInfo['in_start_time']) ? strtotime($orderInfo['in_start_time']) : 0;
        $endTime = isset($orderInfo['in_end_time']) ? strtotime($orderInfo['in_end_time']) : 0;
        $endTime = $endTime > 0 ? strtotime(date('Y-m-d 23:59:59', $endTime)) : $endTime;

        if (empty($orderInfo) || !($curTime >= $startTime && $curTime <= $endTime)) {
            return $transData;
        }
        $dsn = $orderInfo['dsn'];

        $actionInsert = 'insertData';
        $actionUpdate = 'updateData';
        $brandRights = self::getBrandRightsMap($brandId);
        $brandRightsAll = self::getBrandRightsAllMap($brandId);

        foreach ($packageRights as $rights) {
            if (!isset($rightsSourceMap[$rights['rights_source_id']])) {
                continue;
            }
            $totalNum = $rightNum = $rights['rights_data'];
            $sourceRightsType = $rightsSourceMap[$rights['rights_source_id']]['rights_type'];
            $sourceRightsName = $rightsSourceMap[$rights['rights_source_id']]['rights_name'];
            $sourceRightsId = $rights['rights_source_id'];
            $index = $brandId . '_' . $sourceRightsId;
            if (isset($brandRights[$index])) {
                $transData[$sourceRightsId][BrandPackageRights::class][$actionUpdate] = [
                    [
                        'rights_num' => $totalNum,
                        'start_time' => $startTime,
                        'end_time' => $endTime,
                        'rights_status' => BrandPackageRights::STATUS_ON,
                    ],
                    [
                        'brand_id' => $brandId,
                        'rights_source_id' => $sourceRightsId,
                    ]
                ];
            } else {
                $transData[$sourceRightsId][BrandPackageRights::class][$actionInsert] = [
                    [
                        'brand_id' => $brandId,
                        'rights_source_id' => $sourceRightsId,
                        'rights_name' => $sourceRightsName,
                        'rights_num' => $totalNum,
                        'start_time' => $startTime,
                        'end_time' => $endTime,
                        'rights_status' => BrandPackageRights::STATUS_ON,
                    ]
                ];
            }
            if (isset($brandRightsAll[$index])) {
                if ($sourceRightsType == BrandRightsSource::RIGHTS_TYPE_OPEN || $brandRightsAll[$index]['end_time'] < $curTime) {//如果之前的权益已经过期或则未开启
                    $rightNum = $totalNum;
                } else {
                    $oldPackageCount = isset($brandRights[$index]) ? $brandRights[$index]['rights_num'] : 0;
                    $addCount = $totalNum - $oldPackageCount;
                    $addCount = $addCount > 0 ? $addCount : 0;
                    $rightNum = $brandRightsAll[$index]['rights_num'] + $addCount;
                    $totalNum = $brandRightsAll[$index]['total_num'] + $addCount;
                }
                $transData[$sourceRightsId][BrandRightsAll::class][$actionUpdate] = [
                    [
                        'total_num' => $totalNum,
                        'rights_num' => $rightNum,
                        'start_time' => $startTime,
                        'end_time' => $endTime,
                        'rights_status' => BrandRightsAll::STATUS_ON,
                    ],
                    [
                        'brand_id' => $brandId,
                        'rights_source_id' => $sourceRightsId,
                    ],
                ];
            } else {
                $transData[$sourceRightsId][BrandRightsAll::class][$actionInsert] = [
                    [
                        'brand_id' => $brandId,
                        'rights_source_id' => $sourceRightsId,
                        'rights_name' => $sourceRightsName,
                        'total_num' => $totalNum,
                        'rights_num' => $rightNum,
                        'start_time' => $startTime,
                        'end_time' => $endTime,
                        'rights_status' => BrandRightsAll::STATUS_ON,
                    ]
                ];
            }
            if (isset($brandRightsAll[$index])) {
                $transData[$sourceRightsId][BrandRightsRecored::class][$actionInsert] = [
                    [
                        'brand_id' => $brandId,
                        'rights_name' => $sourceRightsName,
                        'rights_source_id' => $sourceRightsId,
                        'recored_type' => BrandRightsRecored::RECORED_TYPE_PACKAGE,
                        'source_id' => $dsn,
                        'operate_uid' => $adminId,
                        'source_data' => json_encode([
                            'order_dsn' => $dsn,
                            'total_num' => $brandRightsAll[$index]['total_num'],
                            'rights_num' => $brandRightsAll[$index]['rights_num'],
                            'start_time' => $brandRightsAll[$index]['start_time'],
                            'end_time' => $brandRightsAll[$index]['end_time'],
                        ]),
                        'operate_data' => json_encode([
                            'total_num' => $totalNum,
                            'rights_num' => $rightNum,
                            'start_time' => $startTime,
                            'end_time' => $endTime,
                            'rights_status' => BrandRightsAll::STATUS_ON
                        ]),
                    ]
                ];

            } else {
                $transData[$sourceRightsId][BrandRightsRecored::class][$actionInsert] = [
                    [
                        'brand_id' => $brandId,
                        'rights_name' => $sourceRightsName,
                        'rights_source_id' => $sourceRightsId,
                        'recored_type' => BrandRightsRecored::RECORED_TYPE_PACKAGE,
                        'source_id' => $dsn,
                        'operate_uid' => $adminId,
                        'source_data' => json_encode([
                            'order_dsn' => $dsn,
                        ]),
                        'operate_data' => json_encode([
                            'total_num' => $totalNum,
                            'rights_num' => $rightNum,
                        ]),
                    ]
                ];
            }
        }

        return $transData;

    }

    /**
     * 获取单个品牌账号
     * @param $brandId
     * @return array|false|mixed
     */
    public static function getOneBrandAccount($brandId)
    {
        $accountInfo = [];
        $result = BrandAccountInfo::getOneByWhere([
            'brand_id' => $brandId,
            'type' => BrandAccountInfo::ACCOUNT_TYPE_BRAND,
            'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED
        ]);
        if ($result && is_array($result)) {
            $accountInfo = $result;
        }
        return $accountInfo;
    }

    /**
     * 获取套餐权益
     * @param $packId
     * @return array|bool
     */
    public static function getPackageRights($packId)
    {
        $packageRights = [];
        $result = BrandPackageRightsConfig::selectList([
            'package_id' => $packId,
            'status' => BrandPackageRightsConfig::STATUS_ON
        ]);
        if ($result && is_array($result)) {
            $packageRights = $result;
        }
        return $packageRights;
    }

    /**
     * 获取套餐权益源Map
     * @param $packageRightsSourceIds
     * @return array
     */
    public static function getPackageRightsSourceMap($packageRightsSourceIds)
    {
        $rightsSourceMap = [];
        $whereBrandRightsSource['id'] = $packageRightsSourceIds;
        $whereBrandRightsSource['data_status'] = BrandRightsSource::STATUS_ON;
        $sResult = BrandRightsSource::selectList($whereBrandRightsSource);
        if ($sResult && is_array($sResult)) {
            $rightsSourceMap = array_column($sResult, null, 'id');
        }
        return $rightsSourceMap;
    }

    /**
     * 获取品牌套餐权益Map
     * @param $brandId
     * @return array
     */
    public static function getBrandRightsMap($brandId)
    {
        $brandRights = [];
        $result = BrandPackageRights::selectList([
            'brand_id' => $brandId,
        ]);
        if ($result && is_array($result)) {
            $brandRights = $result;
        }
        foreach ($brandRights as $key => $rights) {
            $index = $rights['brand_id'] . '_' . $rights['rights_source_id'];
            $brandRights[$key]['index'] = $index;
        }
        if (!empty($brandRights)) {
            $brandRights = array_column($brandRights, null, 'index');
        }
        return $brandRights;
    }

    /**
     * 获取品牌全部权益Map
     * @param $brandId
     * @return array
     */
    public static function getBrandRightsAllMap($brandId)
    {
        $brandRightsAll = [];
        $result = BrandRightsAll::selectList([
            'brand_id' => $brandId,
        ]);
        if ($result && is_array($result)) {
            $brandRightsAll = $result;
        }
        foreach ($brandRightsAll as $key => $rights) {
            $index = $rights['brand_id'] . '_' . $rights['rights_source_id'];
            $brandRightsAll[$key]['index'] = $index;
        }
        if (!empty($brandRightsAll)) {
            $brandRightsAll = array_column($brandRightsAll, null, 'index');
        }
        return $brandRightsAll;
    }

    /**
     * 获取单个权限源数据
     * @param $rightSourceId
     * @return array
     */
    public static function getOneRightsSource($rightSourceId)
    {
        $rightsSource = [];
        $result = BrandRightsSource::getInfo($rightSourceId);
        if ($result && is_array($result)) {
            $rightsSource = $result;
        }
        return $rightsSource;
    }

    /**
     * 增加品牌权益
     * @param $brandId
     * @param $rightsId
     * @param $rightsName
     * @param $rightsNum
     * @param $startTime
     * @param $endTime
     * @return bool
     * @throws \Exception
     */
    public static function insertSource($brandId, $rightsId, $rightsName, $rightsNum, $startTime, $endTime): bool
    {
        $data['brand_id'] = $brandId;
        $data['rights_source_id'] = $rightsId;
        $data['rights_name'] = $rightsName;
        $data['rights_num'] = $rightsNum;
        $data['total_num'] = $rightsNum;
        $data['start_time'] = $startTime;
        $data['end_time'] = $endTime;

        $data['rights_status'] = BaseDbModel::STATUS_NORMAL;
        $res = BrandRightsAll::insertData($data);
        if (!$res) {
            log::error("BrandRightsAll添加数据错误", $data);
            throw new \Exception('添加失败！请重试！');
        }
        return true;
    }

    /**
     * 获取批量品牌权益列表
     * @param $brandIds
     * @return array
     */
    public static function getBrandsSourceList($brandIds): array
    {
        $sourceList = BrandRightsSourceService::getAllSource(['rights_title', 'rights_type', 'id', 'rights_name']);
        if (!$sourceList) {
            return [];
        }
        $sourceList = array_column($sourceList, null, 'id');
        $where['end_time[>=]'] = time();
        $where['brand_id'] = $brandIds;
        $list = BrandRightsAll::selectList($where,
            [
                'id',
                'rights_source_id',
                'total_num',
                'rights_num',
                'brand_id',
                'start_time',
                'end_time',
                'rights_status'
            ]);
        if (!$list) {
            return [];
        }
        foreach ($list as &$item) {
            $item['rights_name'] = $sourceList[$item['rights_source_id']]['rights_name'] ?? '';
            $item['rights_title'] = $sourceList[$item['rights_source_id']]['rights_title'] ?? 0;
            $item['rights_type'] = $sourceList[$item['rights_source_id']]['rights_type'] ?? 0;
            $item['start_time'] = $item['start_time'] ? date("Y-m-d H:i:s", $item['start_time']) : '';
            $item['end_time'] = $item['end_time'] ? date("Y-m-d H:i:s", $item['end_time']) : '';
            $item['status'] = BrandRightsAll::STATUS_DELETE;
            if ($item['end_time'] >= time() && $item['rights_status'] = BrandRightsAll::STATUS_ON) {
                $item['status'] = BrandRightsAll::STATUS_ON;
            }
            if ($item['rights_type'] == BrandRightsSource::RIGHTS_TYPE_NUM) {
                $useCount = self::getNumRightsUseNum($item['brand_id'], $item['rights_name']);
                $item['rights_num'] = $item['total_num'] - $useCount;
            }
        }
        return Common::keyBy($list, 'brand_id');
    }


    public static function getNumRightsUseNum($brandId, $rightsName)
    {
        $num = 0;
        switch ($rightsName) {
            case SourceRightsInterface::CONTENT_RECEIVE:
                $countWhere = [
                    'brand_id' => $brandId,
                    'claim_content_status' => mBrandContent::CLAIM_CONTENT_DONE,
                    'audit_status[!]' => mBrandContent::AUDIT_STATUS_AUTO,
                ];
                $num = mBrandContent::geCountNum($countWhere);
                break;
            default:
                $num = 0;
        }
        return $num;
    }


    /**
     * 批量获取品牌权益列表
     * @return array
     * @daily 暂未使用
     */
    public static function getAllBrandsSourceList(): array
    {
        $sourceList = BrandRightsSourceService::getAllSource(['rights_title', 'rights_type', 'id']);
        if (!$sourceList) {
            return [];
        }
        $sourceList = array_column($sourceList, null, 'id');
        $where['rights_status'] = BaseDbModel::STATUS_NORMAL;
        $where['end_time[>=]'] = time();
        $list = BrandRightsAll::selectList($where,
            ['rights_source_id', 'total_num', 'rights_num', 'brand_id', 'end_time']);
        if (!$list) {
            return [];
        }
        $brandIds = array_unique(array_column($list, 'brand_id'));

        $brandList = Brand::getBrandListByIds($brandIds);
        foreach ($list as &$item) {
            $rightsType = $sourceList[$item['rights_source_id']]['rights_type'] ?? 0;
            $item['end_time'] = $item['end_time'] ? date("Y-m-d H:i:s", $item['end_time']) : '';
            $item['rights_title'] = $sourceList[$item['rights_source_id']]['rights_title'] ?? '';
            $item['rights_type'] = BrandRightsSource::RIGHTS_TYPE_ARR[$rightsType] ?? "未知";
            $item['brand_name'] = $brandList[$item['brand_id']]['brand_name'] ?? '';
        }
        return $list;
    }

    /**
     * 获取批量品牌权益列表
     * @param array $whereExt
     * @return array
     * @deprecated   暂未使用
     */
    public static function getAllList(array $whereExt = []): array
    {
        $sourceList = BrandRightsSourceService::getAllSource(['rights_title', 'rights_type', 'id']);
        if (!$sourceList) {
            return [];
        }
        $sourceList = array_column($sourceList, null, 'id');
        $where['rights_status'] = BaseDbModel::STATUS_NORMAL;
        $where['end_time[>=]'] = time();
        $where = array_merge($whereExt, $where);
        $field = [
            "id",
            "brand_id",
            "rights_source_id",
            "rights_num",
            "total_num",
            "start_time",
            "end_time",
        ];

        $list = BrandRightsAll::selectList($where, $field);
        if (!$list) {
            return [];
        }

        foreach ($list as &$item) {
            $item['rights_title'] = $sourceList[$item['rights_source_id']]['rights_title'] ?? '';
            $item['rights_name'] = $sourceList[$item['rights_source_id']]['rights_name'] ?? '';
            $rightsType = $sourceList[$item['rights_source_id']]['rights_type'] ?? 0;
            $item['rights_type'] = BrandRightsSource::RIGHTS_TYPE_ARR[$rightsType] ?? "未知";
        }
        $list = Common::keyBy($list, 'brand_id');
        $brandIds = array_keys($list);

        $brandList = Brand::getBrandListByIds($brandIds, ['id', 'brand_name']);
        $newList = [];
        foreach ($brandList as $k => $item) {
            $newList[$k] = $item;
            $newList[$k]['source_list'] = $list[$item['id']] ?? [];
        }
        return $newList;
    }

    /**
     * 移除品牌全部权益
     * @param $brandId
     * @return bool|mixed
     */
    public static function removeBrandRights($brandId)
    {
        //获取品牌全部权益
        $where['brand_id'] = $brandId;

        $allRights = BrandRightsAll::selectList($where);

        if (empty($allRights)) {
            return true;
        }

        $targetData = [
            'rights_status' => BaseDbModel::STATUS_DELETE,
            'edittime' => date('Y-m-d H:i:s', time()),
            'rights_num' => 0,
            'total_num' => 0,
        ];

        $rightsRecords = [];

        foreach ($allRights as $rights) {
            $rightsRecord['brand_id'] = $brandId;
            $rightsRecord['source_id'] = 0;
            $rightsRecord['rights_name'] = $rights['rights_name'];
            $rightsRecord['rights_source_id'] = $rights['rights_source_id'];
            $rightsRecord['recored_type'] = BrandRightsRecored::RECORED_TYPE_EXPIRE;
            $rightsRecord['addtime'] = $rightsRecord['edittime'] = $targetData['edittime'];
            $rightsRecord['source_data'] = json_encode($rights);
            $rightsRecord['operate_data'] = json_encode($targetData);
            $rightsRecords[] = $rightsRecord;
        }

        $reserveLevelRights = [];

        $allRightsMap = array_column($allRights, null, 'rights_source_id');

        $brandLevelRights = BrandLevelRightsService::brandLevelRights($brandId);

        foreach ($brandLevelRights as $levelRights) {
            if ($levelRights['rights_status'] != BrandLevelRights::STATUS_NORMAL) {
                continue;
            }
            $reserveRightsNum = $levelRights['rights_num'];
            if (isset($allRightsMap[$levelRights['rights_source_id']])) {
                $aRights = $allRightsMap[$levelRights['rights_source_id']];
                if ($aRights['rights_status'] == BrandRightsAll::STATUS_NORMAL) {
                    //查询record 看是否有类型为8的记录，取出最新一条
                    $record = BrandRightsRecored::getInfo(
                        [
                            'brand_id' => $brandId,
                            'rights_source_id' => $levelRights['rights_source_id'],
                            'recored_type' => BrandRightsRecored::RECORED_TYPE_LEVEL_RECOVERY,
                            'ORDER' => ['id' => 'DESC'],
                        ]
                    );
                    if ($record) {
                        $sourceData = $record['source_data'];
                        $sourceDataArr = json_decode($sourceData,true);
                        $lvRightsNum = $sourceDataArr['lv_rights_num'] ?? 0 ;
                        $reLvRightsNum = $sourceDataArr['re_lv_rights_num'] ?? 0 ;
                        $lRightsNum = $levelRights['rights_num'] - $lvRightsNum + $reLvRightsNum;
                        $reserveRightsNum = $aRights['rights_num'] <= $lRightsNum ? $aRights['rights_num'] : $lRightsNum;
                    } else {
                        $reserveRightsNum = $aRights['rights_num'] <= $levelRights['rights_num'] ? $aRights['rights_num'] : $levelRights['rights_num'];
                    }
                }
            }
            $reserveLevelRights[] = [
                [
                    'reserve_rights_num' => $reserveRightsNum,
                    'reserve_expire_time' => $rights['end_time'] + BrandLevel::LEVEL_RIGHTS_RESERVE_DAYS * 24 * 3600,
                ],
                [
                    'id' => $levelRights['id'],
                ]
            ];
        }

        $result = BrandRightsAll::action(function () use ($where, $rightsRecords, $targetData, $reserveLevelRights) {
            $mResult = BrandRightsAll::updateData($targetData, $where);
            if (!$mResult) {
                return false;
            }
            unset($targetData['total_num']);
            $mResult = BrandPackageRights::updateData($targetData, $where);
            if (!$mResult) {
                return false;
            }
            $mResult = BrandRightsRecored::insert($rightsRecords);
            if (!$mResult) {
                return false;
            }
            if (!empty($reserveLevelRights)) {
                $mResult = mBrandLevelRights::dataMultiUpdate($reserveLevelRights);
                if (!$mResult || $mResult != count($reserveLevelRights)) {
                    return false;
                }
            }
            return true;
        });

        return $result;
    }

    /**
     * 获取搜索权益
     * @param $brandId
     * @return array
     */
    public static function getBrandSearchSource($brandId): array
    {
        $where['rights_status'] = BaseDbModel::STATUS_NORMAL;
        $where['brand_id'] = $brandId;
        $where['end_time[>=]'] = time();
        $where['rights_name'] = SourceRightsInterface::SEARCH_RIGHTS;
        $list = BrandRightsAll::select_master('rights_name', $where);
        $data[$brandId] = $list ?: [];
        return $data;
    }

    /**
     * 更新Es搜索权益缓存
     * @param array $uids
     * @param array $brandIds
     * @return void
     */
    public static function esCacheUpdate($uids, $brandIds)
    {
        EsUpdateCollector::multiInsertForUsers($uids);
        EsUpdateCollector::multiInsertBrandIdsForWikiBasic($brandIds);
    }

    /**
     * 检查更新权益搜索缓存
     * @param int $uid
     * @param int $brandId
     * @param int $rightsId
     * @return bool
     */
    public static function checkBrandRightsEsCache($uid, $brandId, $rightsId)
    {
        if (!$uid) {
            $where['id'] = $brandId;
            $uid = Brand::get('uid', $where);
            if (!$uid) {
                return false;
            }
        }
        $rightsName = BrandRightsSourceService::getNameById($rightsId);
        if (!in_array($rightsName, SourceRightsInterface::SEARCH_RIGHTS)) {
            return true;
        }
        self::esCacheUpdate([$uid], [$brandId]);
        return true;
    }


}